package cc.eddic.practice.concurrency;

import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
public class LogParseWithExecutor {

    LogItemParserTyqImpl logItemParserTyq=new LogItemParserTyqImpl();
    Map<String,List<LogItem>> map=new HashMap<>();

    public Map<String,List<LogItem>> executor(){

        ExecutorService executorService= Executors.newFixedThreadPool(17);
        CountDownLatch latch=new CountDownLatch(LOG_FILE_COUNT);
        //提交所有任务
        for(File f:filesList){
            executorService.submit(()->parse(f,latch));
        }
        try {
            latch.await();
        }catch (InterruptedException e){
            log.error(e.getMessage());
        }
        ExecutorServiceUtil.shutdown(executorService);
        return map;
    }

    //解析每一个log文件
    private void parse(File file,CountDownLatch latch){
        if(log.isDebugEnabled()) log.debug("{}",file.getName());
        List<LogItem> logItemList = readList(file.getPath()).stream().map(filestring -> logItemParserTyq.parse(filestring)).filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
        latch.countDown();
        map.put(file.getName(),logItemList);
    }

    //parse：读log文件
    public List<String> readList(String textFileName) {
        return read(textFileName).collect(Collectors.toList());
    }
    //parse：读每一行
    public Stream<String> read(String textFileName) {
        try {
            val p = Paths.get(textFileName);
            return Files.lines(p);
        } catch (IOException e) {
            if (log.isDebugEnabled()) log.debug("{}", textFileName);
            return null;
        }
    }


    private List<File> conut(){
        List<File> filesList = new ArrayList<>();
        //获取文件夹里的所有log文件
        String folderName="D:\\SONY培训\\nginx-logs\\nginx-logs";
        fileResult(new File(folderName), filesList);
        return filesList.stream().filter(file -> file.getName().endsWith(".log")).collect(Collectors.toList());
    }

    private void fileResult(File file, List<File> filesList) {
        //获取文件夹下的所有文件
        val files = file.listFiles();
        if (files == null) {
            return;
        }
        for (val f : files) {
            if (f.isDirectory()) {
                fileResult(f, filesList);
            } else filesList.add(f);
        }
    }
    List<File> filesList =conut();
    private final int LOG_FILE_COUNT=filesList.size();

}
